<template>
  <div>
    <el-dialog v-model="dialogVisible" title="分配菜单和按钮权限" width="30%">
      <el-tree ref="treeRef" :data="treeData" show-checkbox node-key="id" default-expand-all :default-checked-keys="selectId" :props="defaultProps" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm($parent)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { RoleData, MunuData } from '@/utils/api/acl/role/type'
import { reqAllMenuList, reqSetPermisstion } from '@/utils/api/acl/role'

// 对话框的显示与隐藏
const dialogVisible = ref(false)
// 树型控件数据
const treeData = ref<MunuData[]>([])
// 选中的ID
const selectId = ref<number[]>([])
// tree的ref
const treeRef = ref()
const rowId = ref<number>()

// 树型控件的属性
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 对话框的显示与隐藏
const changeShow = (row: RoleData) => {
  dialogVisible.value = true
  rowId.value = row.id!
  getMenuList(row.id!)
}

// 获取菜单权限
const getMenuList = async (id: number) => {
  const res = await reqAllMenuList(id)
  if (res.data.code == 200) {
    treeData.value = res.data.data
    filterSelectTree(res.data.data)
  }
}

// 过滤出选择的树型节点
const filterSelectTree = (tree: any) => {
  tree.forEach((i1: any) => {
    if (i1.children.length > 0) {
      filterSelectTree(i1.children)
    } else {
      if (i1.select) {
        selectId.value.push(i1.id)
      }
    }
  })
}

// 确定按钮
const confirm = async ($parent: any) => {
  const selectAllId: number[] = []
  treeRef.value.getCheckedNodes().forEach((item: MunuData) => {
    selectAllId.push(item.id)
  })
  const res = await reqSetPermisstion(rowId.value!, selectAllId)
  if (res.data.code == 200) {
    ElMessage.success('修改权限成功')
    $parent.$parent.getRoleTable($parent.$parent.currentPage)
    dialogVisible.value = false
  }
}

defineExpose({ changeShow })
</script>

<style scoped></style>
